<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
  <style>
    .uploadImg .el-form-item__label::before{
      content: '*';
      color: #F56C6C;
      margin-right: 4px;
    }

  </style>
</head>
<body>
  <div class="addBrand-container" id="member-add-app">
    <div class="container">
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        :inline="false"
        label-width="180px"
        class="demo-userForm"
      >
        <el-form-item label="账号:" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入账号" maxlength="20"/>
        </el-form-item>

        <el-form-item label="手机号" >
          <el-input v-model="userForm.phone" placeholder="请输入手机号" placeholder="请输入手机号"  maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="userForm.password" placeholder="请输入密码" maxlength="20"/>
        </el-form-item>

        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>

        <div>
          <el-form-item label="头像:"  class="uploadImg">
            <el-upload
                    class="avatar-uploader"
                    action="/common/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :on-change="onChange"
                    ref="upload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>

        <div class="subBox address">
          <el-form-item>
            <el-button  @click="goBack()">取消</el-button>
            <el-button type="primary" @click="submitForm('userForm', false)">保存</el-button>
            <el-button v-if="actionType == 'add'" type="primary" class="continue" @click="submitForm('userForm', true)">
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="../../plugins/vue/vue.js"></script>
    <!-- 引入组件库 -->
    <script src="../../plugins/element-ui/index.js"></script>
    <!-- 引入axios -->
    <script src="../../plugins/axios/axios.min.js"></script>
    <script src="../../js/request.js"></script>
    <script src="../../api/user.js"></script>
    <script src="../../js/validate.js"></script>
    <script src="../../js/index.js"></script>
    <script>
      new Vue({
        el: '#member-add-app',
        data() {
          return {
            id: '',

            //判断是否有保存并继续添加按钮
            actionType : '',

            userForm : {
              sex:"男"
            },

            //校验规则
            rules: {
              name: [
                { required: true, message: '账号', trigger: 'blur' },
              ],
              sex: [
                { required: true, message:"性别", trigger: 'blur' },
              ],
              phone: [
                { required: true, message:"手机号", trigger: 'blur' },
              ],
              password:[
                {required:true,message:"密码",trigger:"blur"}
              ]
            },

            //在得到待编辑的用户信息后,将用户头像赋值,便于显示
            imageUrl:"",

          }
        },
        computed: {},
        created() {

          //新增时,首先根据url的id为空,判断 是edit or add ,从而显示不同的按钮
          this.id = requestUrlParam('id')
          this.actionType = this.id ? 'edit' : 'add'
          if (this.id) {
            this.init()
          }
        },
        mounted() {
        },





        methods: {


          /**
           *编辑时页面回显
           * 根据用户id查询用户信息
           * @returns {Promise<void>}
           */
          async init () {
            queryUserById(this.id).then(res => {
              console.log(res)
              if (String(res.code) === '1') {
                console.log(res.data)
                this.userForm = res.data
                //0是男,1是女
                this.userForm.sex = res.data.sex === '0' ? '女' : '男'

                this.imageUrl = `/common/download?name=${res.data.avatar}`
                console.log(this.imageUrl)

              } else {
                this.$message.error(res.msg || '操作失败')
              }
            })
          },


          /**
           * 提交userForm,
           * 根据st ("add" or "save")判断添加 or 新增,从而请求不同的网址
           * @param formName
           * @param st 是否继续添加
           */
          submitForm (formName, st) {
            this.$refs[formName].validate((valid) => {
              if (valid) {

                //新增用户
                if (this.actionType === 'add') {
                  const params = {
                    ...this.userForm,
                    sex: this.userForm.sex === '女' ? '0' : '1'
                  }
                  addUser(params).then(res => {
                    if (res.code === 1) {
                      this.$message.success('员工添加成功！')

                      //如果不是保存并继续添加,则调用goBack()返回上一级页面,否则清空userForm,继续添加
                      if (!st) {
                        this.goBack()
                      } else {
                        this.userForm = {}
                      }
                    }
                    else {
                      this.$message.error(res.msg || '操作失败')
                    }
                  }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                  })
                }

                //修改用户信息
                else {
                  const params = {
                    ...this.userForm,
                    sex: this.userForm.sex === '女' ? '0' : '1'
                  }
                  //修改完用户信息,则调用goBack()返回上一级页面
                  editUser(params).then(res => {
                    console.log("editUser",res)
                    if (res.code === 1) {

                      this.$message.success('员工信息修改成功！')
                      this.goBack()
                    } else {
                      this.$message.error(res.msg || '操作失败')
                    }
                  }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                  })
                }
              }
              //提交表单错误
              else {
                console.log('error submit!!')
                return false
              }
            })
          },


          /**
           * 返回上以及菜单,并将goBack 置为False
           */
          goBack(){
            window.parent.menuHandle({
              id: '2',
              url: '/backend/page/user/list.html',
              name: '员工管理'
            },false)
          },




          handleAvatarSuccess (response, file, fileList) {
            console.log(response)
            // 拼接down接口预览
            if(response.code === 0 && response.msg === '未登录'){
              window.top.location.href = '/backend/page/login/login.html'
            }else{
              this.imageUrl = `/common/download?name=${response.data}`
              this.userForm.avatar = response.data
            }
          },

          onChange (file) {
            if(file){
              const suffix = file.name.split('.')[1]
              const size = file.size / 1024 / 1024 < 2
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                this.$refs.upload.clearFiles()
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!')
                return false
              }
              return file
            }
          },

        }
      })
    </script>
</body>
</html>